package com.buddha.api.security;

import com.buddha.api.common.CaptchaException;
import com.buddha.api.common.Constants;
import com.buddha.api.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginFailureHandle loginFailureHandle;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        if ("/login".equals(uri) && "POST".equals(method)){
            try {
                validKaptcha(request);
            }catch (CaptchaException e){
                loginFailureHandle.onAuthenticationFailure(request,response,e);
            }
        }
        filterChain.doFilter(request,response);
    }

    private void validKaptcha(HttpServletRequest request) {
        String kaptcha = request.getParameter("captcha");
        String token = request.getParameter("token");
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(token)){
            throw new CaptchaException("验证码错误");
        }
        if (!kaptcha.equals(redisUtil.hget(Constants.CAPTCHA_KEY,token))){
            throw new CaptchaException("验证码错误");
        }
        redisUtil.hdel(Constants.CAPTCHA_KEY,token);
    }
}
